<template>
  <div class="json-editor">
    <textarea id="code-editor" ref="textarea" />
  </div>
</template>

<script>
import CodeMirror from 'codemirror'
import 'codemirror/addon/lint/lint.css'
import 'codemirror/lib/codemirror.css'
import 'codemirror/theme/rubyblue.css'
require('script-loader!jsonlint')
import 'codemirror/mode/javascript/javascript'
import 'codemirror/addon/lint/lint'
import 'codemirror/addon/lint/json-lint'

export default {
  name: 'JsonEditor',
  props: {
    value: {
      type: [Object, Array, String],
      default: () => {
        return {}
      }
    },
    theme: {
      type: String,
      default: 'dark',
      validator(value) {
        if (['dark', 'light'].includes(value)) {
          return true
        } else {
          console.error('属性theme值必须是dark或light')
          return false
        }
      }
    }
  },
  data() {
    return {
      jsonEditor: false
    }
  },
  watch: {
    value(value) {
      const editorValue = this.jsonEditor.getValue()
      if (value !== editorValue) {
        this.jsonEditor.setValue(JSON.stringify(this.value, null, 2))
      }
    },
    theme(val) {
      if (this.jsonEditor) {
        this.jsonEditor.setOption('theme', val === 'dark' ? 'rubyblue' : '')
      }
    }
  },
  mounted() {
    const textarea = document.getElementById('code-editor')
    this.jsonEditor = CodeMirror.fromTextArea(textarea, {
      lineNumbers: true,
      mode: 'application/json',
      gutters: ['CodeMirror-lint-markers'],
      theme: this.theme === 'dark' ? 'rubyblue' : '',
      lint: true
    })
    this.jsonEditor.setValue(JSON.stringify(this.value, null, 2))
    this.jsonEditor.on('change', cm => {
      this.$emit('changed', cm.getValue())
      this.$emit('input', cm.getValue())
    })
  },
  methods: {
    getValue() {
      return this.jsonEditor.getValue()
    }
  }
}
</script>

<style lang="scss" scoped>
.json-editor {
  width: 100%;
  height: 100%;
  position: relative;

  ::v-deep {
    .CodeMirror {
      height: auto;
      min-height: 300px;
    }

    .CodeMirror-scroll {
      min-height: 300px;
    }

    .cm-s-rubyblue span.cm-string {
      color: #F08047;
    }
  }
}
</style>
